package com.bw.module_video_detail.test_exoplayer

import android.net.Uri
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultLoadControl


import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.bumptech.glide.util.Util
import com.bw.module_video_detail.R
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSource
import com.google.android.exoplayer2.upstream.cache.CacheDataSource
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor
import com.google.android.exoplayer2.upstream.cache.SimpleCache
import java.io.File

class ExoActivity : AppCompatActivity() {
    private lateinit var playerView: PlayerView
    private lateinit var exoPlayer: ExoPlayer
    @OptIn(UnstableApi::class) override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_exo)
        playerView = findViewById(R.id.player_view)



        //------------------缓存相关-------------
        //1:目录
        val cacheDir = File(cacheDir, "exo_video_cache").apply {
            if (!exists()) mkdirs()
        }
        //2：缓存实例
        val cache = SimpleCache(cacheDir, LeastRecentlyUsedCacheEvictor(100 * 1024 * 1024))
        //3：缓存工厂
        val dataSourceFactory = DefaultDataSource.Factory(this)
        val cacheFactory = CacheDataSource.Factory()
            .setCache(cache)
            .setUpstreamDataSourceFactory(dataSourceFactory)
            .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) //混略缓存作物==错误

        //4:媒体资源
        val mediaItem = MediaItem.fromUri(Uri.parse(""))
        val mediaSource = ProgressiveMediaSource.Factory(cacheFactory)//缓存工厂
            .createMediaSource(mediaItem)

        //-------------------缓冲相关---------------------
        // 创建默认的 LoadControl
        val loadControl = DefaultLoadControl.Builder()
            .setBufferDurationsMs(
                5000, //最小缓冲时间
                5000,//最大缓冲时间
                2000, //开始播放前需要缓冲的时间，通常设置为 2-5 秒，首播，缓冲中够2秒播放
                3000 //重新缓冲后需要缓冲的时间，通常设置为 1-3 秒，播放中断(缓存耗尽)，重新缓存够3秒才播放
            )
            .build()



        //exoPlayer实例
        exoPlayer = ExoPlayer.Builder(this)
            .setLoadControl(loadControl) //设置缓存
            .build()
        playerView.player = exoPlayer

//        exoPlayer.setMediaSource(mediaSource)
        exoPlayer.prepare()
        exoPlayer.playWhenReady = true



    }
}